<?php

namespace app\admin\model\shopro;

use think\Model;

/**
 * Code模型
 */
class Code extends Model
{
    protected $name = 'shopro_code';
    
    protected $autoWriteTimestamp = true;
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    
    /**
     * 获取下一个可用的code编号
     * 
     * @return string
     */
    public static function getNextCode()
    {
        // 获取当前最大的编号 - 使用主键ID来获取最大的code
        $maxRecord = self::order('id', 'desc')->find();
        
        \think\Log::write('getNextCode - maxRecord: ' . ($maxRecord ? json_encode($maxRecord->toArray()) : 'null'));
        
        if (!$maxRecord) {
            // 如果没有记录，从第一个开始
            $nextNumber = 1;
            \think\Log::write('getNextCode - 没有记录，从1开始');
        } else {
            // 提取数字部分
            $maxCode = $maxRecord->code;
            $number = intval(substr($maxCode, 3)); // 去掉RWA前缀
            $nextNumber = $number + 1;
            \think\Log::write('getNextCode - 最大code: ' . $maxCode . ', 提取数字: ' . $number . ', 下一个数字: ' . $nextNumber);
        }
        
        // 检查是否超过限制
        if ($nextNumber > 1000000) {
            throw new \Exception('Code数量已达上限1,000,000份');
        }
        
        // 格式化为8位数字
        $newCode = 'DD' . str_pad($nextNumber, 8, '0', STR_PAD_LEFT);
        \think\Log::write('getNextCode - 生成新code: ' . $newCode);
        
        return $newCode;
    }
    
    /**
     * 批量生成codes
     * 
     * @param int $orderId 订单ID
     * @param int $count 生成数量
     * @return array
     */
    public static function generateCodes($orderId, $count)
    {
        $codes = [];
        
        for ($i = 0; $i < $count; $i++) {
            $code = self::getNextCode();
            
            // 创建记录
            $codeModel = new self();
            $codeModel->code = $code;
            $codeModel->order_id = $orderId;
            $codeModel->save();
            
            $codes[] = $code;
        }
        
        return $codes;
    }
    
    /**
     * 根据订单ID获取codes
     * 
     * @param int $orderId
     * @return array
     */
    public static function getCodesByOrderId($orderId)
    {
        return self::where('order_id', $orderId)
            ->order('id', 'asc')
            ->column('code');
    }
    
    /**
     * 根据code查找订单ID
     * 
     * @param string $code
     * @return int|null
     */
    public static function getOrderIdByCode($code)
    {
        $record = self::where('code', $code)->find();
        return $record ? $record->order_id : null;
    }
    
    /**
     * 验证code是否存在
     * 
     * @param string $code
     * @return bool
     */
    public static function codeExists($code)
    {
        return self::where('code', $code)->count() > 0;
    }
    
    /**
     * 获取code统计信息
     * 
     * @return array
     */
    public static function getCodeStats()
    {
        $total = self::count();
        $used = $total;
        $remaining = 1000000 - $used;
        
        return [
            'total' => $total,
            'used' => $used,
            'remaining' => $remaining,
            'percentage' => round(($used / 1000000) * 100, 2)
        ];
    }
}
